﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wiwi.Models;
using Wiwi.ViewModels;
using System.Web.Security;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Web.Mvc;
namespace Wiwi.Controllers
{
    public class HomeController : ApplicationController
    {
        public ActionResult Testwin()
        {
            int i = 1;
            return View(i);
        }
        public ActionResult Testwin1()
        {
            int i = 1;
            return PartialView("testwin1", i);
        }
        private void cli_SendNotificationCompleted(object sender, ServiceReference1.SendNotificationCompletedEventArgs args)
        {
            string str = args.Result.ToString();
        }
        public ActionResult Index()
        {
            WiwiEntities1 db = new WiwiEntities1();

            //Guid guw = new Guid("AE6AE140-07E7-4950-B651-A5B86FDAA45D");
            //ServiceReference1.Service1Client cli = new ServiceReference1.Service1Client();
            //cli.SendNotificationCompleted += new EventHandler<ServiceReference1.SendNotificationCompletedEventArgs>(cli_SendNotificationCompleted);
            //cli.SendNotificationAsync(guw);
            
            ProfileView pv = new ProfileView();
            List<A_vWant> WntList = new List<A_vWant>();
            List<A_vCloud> cld = (from cl in db.A_vCloud select cl).ToList();
            var wnt = (from wn in db.GetWants("ALL", null,"1") select wn).ToList();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                //nw.NewPitch = GetNewPitchForWant(wn.WantID, db);
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            List<A_vCloud> OutCloud = new List<A_vCloud>();
            int? maxCnt = (from cl in cld select cl.Cnt).Max();
            foreach (var cl in cld)
            {
                A_vCloud c = new A_vCloud();
                c.keyword = cl.keyword;
                c.Cnt =cl.Cnt;
                c.KeywordID = cl.KeywordID;
                c.MaxCnt =int.Parse(maxCnt.ToString());
                int cnt = int.Parse(cl.Cnt.ToString());
                c.Scrore = (cnt / c.MaxCnt) * 100;
                OutCloud.Add(c);
            }
            pv.Want = WntList;
            pv.Cloud = OutCloud;
            //popular wants

            List<A_vWant> PopWntL = new List<A_vWant>();
            var popWnt = (from wn in db.A_PopularWant() select wn).ToList();
            foreach (A_vWant wn in popWnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                //nw.NewPitch = GetNewPitchForWant(wn.WantID, db);
                nw.MtosCount = 0;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                PopWntL.Add(nw);
            }
            pv.WantPopular = PopWntL;
            return View(pv);
        }
        public ActionResult WiwiDetails(Guid wntID, Guid? UsrID)
        {
            ProfileView pv = new ProfileView();
            WiwiEntities1 db = new WiwiEntities1();
            List<A_vWant> WntList = new List<A_vWant>();
            Guid gu = new Guid(wntID.ToString());
            var wnt = (from wn in db.GetWants("ALL", null,null) where wn.WantID == wntID select wn).Take(1).ToList();
            if (UsrID != null) wnt = (from wn in db.GetWants("ALL", null, null) where wn.WantID == wntID select wn).Take(1).ToList();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                gu = wn.UserID;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            A_vUserTable UT = db.A_vUserTable.SingleOrDefault(c => c.UserID == gu);
            pv.Usr = UT;
            pv.Want = WntList;
            return View(pv);
        }
        public JsonResult TopWantsCount(string DT)
        {
            string[] Arr = DT.Split(',');
            //lastdate = monthFunc + "/" + currentFunc.getDate() + "/" + currentFunc.getFullYear() + "/" + currentFunc.getHours() + "/" + currentFunc.getMinutes() + "/" + currentFunc.getSeconds();
            DateTime LastDT = new DateTime(int.Parse(Arr[2]), int.Parse(Arr[0]), int.Parse(Arr[1]), int.Parse(Arr[3]), int.Parse(Arr[4]), int.Parse(Arr[5]));
            WiwiEntities1 db = new WiwiEntities1();
            var wnt = (from wn in db.GetWants("ALL", null,null) where wn.WiwiDate > LastDT select wn).ToList();
            return Json(wnt.Count.ToString(), JsonRequestBehavior.AllowGet);
        }
        public JsonResult IndexWants()
        {
            ProfileView pv = new ProfileView();
            WiwiEntities1 db = new WiwiEntities1();
            //var wnt = (from wn in db.A_vWant where wn.IsStarted == true && wn.IsClosed == false select wn).Take(5).ToList(); 
            List<A_vWant> WntList = new List<A_vWant>();
            var wnt = (from wn in db.GetWants("ALL", null,null) select wn).Take(5).ToList();
            Guid gu;
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                gu = wn.UserID;
                //nw.NewPitch = GetNewPitchForWant(wn.WantID, db);
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            pv.Want = WntList;
            return Json(WntList, JsonRequestBehavior.AllowGet);
        }

        public JsonResult KeyWords(string tag)
        {
            WiwiEntities1 db = new WiwiEntities1();
            var kw = from ki in db.A_KeyWord orderby ki.keyword where ki.keyword.StartsWith(tag) select ki.keyword;
            return Json(kw);
        }
        
        [Authorize]
        public ActionResult ReWant()
        {
            ProfileView pv = new ProfileView();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            List<A_vWant> WntList = new List<A_vWant>();
            var wnt = (from wn in db.GetWants("Close", gusr,null) select wn).ToList();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                A_vWant wE = WntList.SingleOrDefault(c => c.WantID == wn.WantID);
                if (wE == null) WntList.Add(nw);
            }
            pv.Want = WntList;
            return View(pv);
        }

        [Authorize]
        public ActionResult ReWantSave(string Wuid)
        {
            Guid gu = new Guid(Wuid);
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            WiwiEntities1 db = new WiwiEntities1();
            A_Want_Wanter wu = db.A_Want_Wanter.SingleOrDefault(c => c.Want_Wanter_RelID == gu);
            var keywords = (from wk in db.A_WantKeyword where wk.WantID == wu.WantID select wk).ToList();
            A_Want wnt = db.A_Want.SingleOrDefault(c => c.WantID == wu.WantID);
            A_Want Nw = new A_Want();
            Nw.WantID = Guid.NewGuid();
            Nw.WantDesc = wnt.WantDesc;
            db.AddToA_Want(Nw);
            db.SaveChanges();
            foreach (var kw in keywords)
            {
                A_WantKeyword kwd = new A_WantKeyword();
                kwd.WantID = Nw.WantID;
                kwd.KeyWordID = kw.KeyWordID;
                db.AddToA_WantKeyword(kwd); 
                db.SaveChanges();
            }
            A_Want_Wanter us = new A_Want_Wanter();
            us.Want_Wanter_RelID = Guid.NewGuid();
            us.IsCurrentOwner = true;
            us.WantID = Nw.WantID;
            us.UserID = gusr;
            us.IsClosed = false;
            us.IsCreator = true;
            us.ExpiryDate = DateTime.Now.AddDays(7);
            us.WiwiDate = DateTime.Now;
            us.IsReWiwi = true;
            us.ParentWantID = wu.Want_Wanter_RelID;
            db.AddToA_Want_Wanter(us);
            db.SaveChanges();
            return RedirectToAction("../Home/Profile/");
        }

        public ActionResult Profile()
        {
            ProfileView pv = new ProfileView();
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            var wnt = (from wn in db.A_vMyWants where wn.UserID == gu select wn).ToList();
            List<WantsonProfile> MyWants = new List<WantsonProfile>();
            foreach (A_vMyWants wn in wnt)
            {
                WantsonProfile p = new WantsonProfile();
                A_vMyWants Np = new A_vMyWants();
                List<A_vNewPitchesDetails> det = CommonFunc.GetListOfWantDetailsForUser(wn.WantID, gu, db);
                Np.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                Np.UserID = wn.UserID;
                Np.WiwiDate = wn.WiwiDate;
                Np.ExpiryDate = wn.ExpiryDate;
                Np.IsCreator = wn.IsCreator;
                Np.WantDesc = wn.WantDesc;
                Np.WantID = wn.WantID;
                Np.WantUsers = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                Np.MeTos = CommonFunc.GetMetoCountForWant(wn.WantID, db);
                Np.NewPitches = CommonFunc.GetNewPitchForWant(wn.Want_Wanter_RelID, db);
                Np.Tags = wn.Tags;
                p.PitchesDetails = det;
                p.UserWants = Np;
                MyWants.Add(p);
            }
            
            List<WantsonProfile> Pitches = new List<WantsonProfile>();
            var pit = (from pt in db.A_sNewPitches(gu) select pt).ToList();
            foreach (A_vNewPitches np in pit)
            {
                WantsonProfile p = new WantsonProfile();
                A_vNewPitches Np = new A_vNewPitches();
                List<A_vNewPitchesDetails> det = CommonFunc.GetListOfPitchesDetailsForSupp(np.WantID, gu, db);
                Np.WantDesc = np.WantDesc;
                Np.WantID = np.WantID;
                Np.MeTos = CommonFunc.GetMetoCountForWant(np.WantID, db);
                p.PitchesDetails = det;
                p.NewPitches = Np;
                Pitches.Add(p);
            }
            pv.SuppPitches = Pitches;
            pv.MyWants = MyWants;
            return View(pv);
        }
                
        public ActionResult EditProfile()
        {
            WiwiEntities1 db = new WiwiEntities1();
            UserProfile pro = new UserProfile();
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            A_UserTable UT = db.A_UserTable.SingleOrDefault(c => c.UserID == gu);
            pro.Firstname = UT.FName;
            pro.Lastname = UT.Lname;
            pro.ContactNo = UT.ContactNo;
            pro.Sex = UT.Sex;
            pro.Bio = UT.Bio;
            if(UT.BirthDate!=null) pro.BirthDate = UT.BirthDate.Value.Day.ToString() + "/" + UT.BirthDate.Value.Month.ToString() + "/" + UT.BirthDate.Value.Year.ToString();
            pro.Lastname = UT.Lname;
            pro.Email = usr.Email;
            if (UT.photo != null) pro.photo = "1";
            pro.UsrID = UT.UserID.ToString();
            return View(pro);
        }

        public ActionResult ShowUserImage(string Uid)
        {
            WiwiEntities1 db = new WiwiEntities1();
            Guid gu = new Guid(Uid);
            A_UserTable UT = db.A_UserTable.SingleOrDefault(c => c.UserID == gu);
            if (UT == null) return null;
            var imageData = UT.photo;
            if (UT.photo != null) return File(imageData, "image/jpg");
            else return null;
        }

        [HttpPost]
        public ActionResult EditProfile(UserProfile pro)
        {
            HttpPostedFileBase file = Request.Files["file1"];
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gu = new Guid(usr.ProviderUserKey.ToString());
            A_UserTable UT = db.A_UserTable.SingleOrDefault(c => c.UserID == gu);
            UT.FName = pro.Firstname;
            UT.Lname = pro.Lastname;
            UT.Bio = pro.Bio;
            UT.Sex = pro.Sex;
            UT.ContactNo = pro.ContactNo;
          
            if (Request.Form["DtDay"].ToString() != "" && Request.Form["DtMon"].ToString() != "" && Request.Form["Dtyr"].ToString()!="")
            {
                DateTime dt = new DateTime(int.Parse(Request.Form["Dtyr"].ToString()),int.Parse(Request.Form["DtMon"].ToString()),int.Parse(Request.Form["DtDay"].ToString()));
                UT.BirthDate = dt;
            }
            usr.Email = pro.Email;
            Membership.UpdateUser(usr);
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    byte[] bytes = new byte[file.ContentLength];
                    file.InputStream.Read(bytes, 0, file.ContentLength);
                    UT.photo = bytes;
                }
            }
            db.SaveChanges();
            return RedirectToAction("EditProfile");
        }
        public ActionResult UserPublicProfile(string Uid)
        {
            WiwiEntities1 db = new WiwiEntities1();
            Guid GuUser = new Guid(Uid);
            ProfileView pv = new ProfileView();
            var wnt = (from wn in db.A_vWant where wn.UserID == GuUser && wn.IsClosed == false orderby wn.WiwiDate descending select wn).ToList();
            List<A_vWant> WntList = new List<A_vWant>();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.NewPitch = CommonFunc.GetNewPitchForWant(wn.Want_Wanter_RelID, db);
                nw.Tags = wn.Tags;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            pv.Want = WntList;
            A_vUserTable UT = db.A_vUserTable.SingleOrDefault(c => c.UserID == GuUser);
            pv.Usr = UT;
            return View(pv);
        }

        public ActionResult MoreRecent(string pagecnt)
        {
            int TotPages = int.Parse(pagecnt) * 1;
            ProfileView pv = new ProfileView();
            WiwiEntities1 db = new WiwiEntities1();
            List<A_vWant> WntList = new List<A_vWant>();
            var wnt = (from wn in db.GetWants("ALL", null,null) select wn).Take(TotPages).ToList();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            pv.Want = WntList;
            return View(pv);
        }
        public JsonResult MoreRecentAjax(string pageno)
        {
            int TotPages = int.Parse(pageno) * 1;
            WiwiEntities1 db = new WiwiEntities1();
            List<A_vWant> WntList = new List<A_vWant>();
            var wnt = (from wn in db.GetWants("ALL", null,null) select wn).Take(TotPages).ToList();
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            return Json(WntList, JsonRequestBehavior.AllowGet);
        }
        public ActionResult KeyWordWants(string KeyWordID)
        {
            ProfileView pv = new ProfileView();
            WiwiEntities1 db = new WiwiEntities1();
            Guid guKey = new Guid(KeyWordID);
            List<A_vWant> WntList = new List<A_vWant>();
            var wnt = (from wn in db.A_vWant join wk in db.A_WantKeyword on wn.WantID equals wk.WantID where wk.KeyWordID ==guKey && wn.IsClosed == false && wn.ExpiryDate > DateTime.Now select wn);
            foreach (A_vWant wn in wnt)
            {
                A_vWant nw = new A_vWant();
                nw.FName = wn.FName;
                nw.Lname = wn.Lname;
                nw.Tags = wn.Tags;
                nw.Want_Wanter_RelID = wn.Want_Wanter_RelID;
                nw.UserID = wn.UserID;
                nw.IsCreator = wn.IsCreator;
                nw.WantbyUsr = CommonFunc.GetListOfMetoForWant(wn.WantID, db, wn.UserID);
                nw.WiwiDate = wn.WiwiDate;
                nw.WantDesc = wn.WantDesc;
                nw.IsClosed = wn.IsClosed;
                nw.WantID = wn.WantID;
                WntList.Add(nw);
            }
            var sortedlist = (from wn in WntList orderby wn.WiwiDate descending select wn).ToList();
            pv.Want = sortedlist;
            return View(pv);
        }
        [AcceptAjax]
        public ActionResult About1()
        {
            A_Want wn = new A_Want();
            wn.WantDesc = "Mash 1234";
            return PartialView("About1", wn);
            //return Json(new
            //{
            //    Html= PartialView("About1", wn)
            //  }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult About()
        {
            return View();
        }
        public ActionResult Registration()
        {
            ViewData["PostBackAction"] = "Registration";
            return View();
        }
        [HttpPost]
        public ActionResult Registration(RegistrationTop rg)
        {
            return RedirectToAction("Register", "Account", new { fname = rg.Firstname, lname= rg.Lastname, email = rg.email, usr = rg.UserName });
        }
        [AcceptVerbs(HttpVerbs.Get)]
        [ActionName("File")]
        public ActionResult File(string FileID)
        {
            long attid = long.Parse(FileID);
            WiwiEntities1 db = new WiwiEntities1();
            A_Attachment att = db.A_Attachment.SingleOrDefault(c => c.At_ID == attid);
            byte[] fileBytes = att.At_Byte;
            string fileName = att.At_Name;
            string extn = System.IO.Path.GetExtension(att.At_Name);
            return new BinaryResult(fileBytes,fileName,extn);
        }
    }


}

